const express = require("express");
const mongoose = require("mongoose");
const userDebugger = require("debug")("app:user");
const Response = require("../utils/response");

const userSchema = new mongoose.Schema({
  phoneNumber: {
    type: Number,
    required: true,
    validate: {
      async: true,
      message: "Phone number should be unique.",
      validator: async function (number) {
        const numbers_found = await User.find({ phoneNumber: number });
        if (numbers_found.length) {
          return Promise.resolve(false);
        }
        return Promise.resolve(true);
      },
    },
  },
  password: { type: String, required: true },
  balance: { type: Number, default: 0 },
  history: {
    type: [
      {
        product_id: {
          type: mongoose.Schema.Types.ObjectId,
          ref: "Product",
        },
        time: mongoose.Schema.Types.Date,
        number: Number,
      },
    ],
    default: [],
  },
});

const User = mongoose.model("User", userSchema);

async function createUser(phoneNumber, password, balance) {
  const user = new User({
    phoneNumber,
    password,
    balance,
  });
  const result = await user.save();
  return result;
}

router = express();

router.get("/test", (req, res) => {
  const { query } = req;
  query.state = "success";
  res.send(query);
});

router.post("/add", async function (req, res) {
  const { phoneNumber, password, balance } = req.query;
  try {
    const data = await createUser(phoneNumber, password, balance);
    const result = new Response(data);
    userDebugger(result);
    res.send(result);
  } catch (ex) {
    let result = [];
    for (field in ex.errors) {
      const message = ex.errors[field].message;
      result.push(message);
    }
    userDebugger("ERROR:", result);
    res.send(new Response(null, result, "Duplicate"));
  }
});

async function validateUser(phoneNumber, password) {
  const usersFound = await User.find({ phoneNumber }).populate(
    "history.product_id"
  );
  // If phone number not found
  if (!usersFound.length) {
    const result = new Response(null, "Phone number not exist", "PhoneNumber");
    return result;
  }
  // If password is incorrect
  const { password: passwordFound } = usersFound[0];
  if (password != passwordFound) {
    const result = new Response(null, "Incorrect password", "Password");
    return result;
  }
  // Success
  return new Response(usersFound[0]);
}

router.get("/login", async function (req, res) {
  const { phoneNumber, password } = req.query;
  const result = await validateUser(phoneNumber, password);
  res.send(result);
  return;
});

router.put("/changePassword", async function (req, res) {
  const { oldPassword, newPassword, phoneNumber } = req.query;
  let result = await validateUser(phoneNumber, oldPassword);
  if (result.success) {
    const { _id } = result.data;
    result = await User.updateOne({ _id }, { $set: { password: newPassword } });
    result = new Response(result);
  }
  res.send(result);
});

module.exports = router;
